package com.hustbaidu.hustmap;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class LectureListActivity extends Activity {
	private static final String NAME_SPACE = "http://webservice.mapmanage.hustbaidu.com/"; 
	private static final String URL_LECTURE = "http://10.0.2.2:8080/hustmapmanage/webServices/lectureWebService";
	
	private Button refreshLectureWidget;
	private ImageButton selectPlaceWidget;
	private ImageButton selectTypeWidget;
	private ImageButton selectTimeWidget;
	private ListView lectureListWidget;
	
	private int placeId;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lecture_list_layout);
		
		PlaceInfo place = getIntent().getExtras().getParcelable("place");
		placeId = place.getId();
		
		refreshLectureWidget = (Button)findViewById(R.id.refresh_lecture);
		refreshLectureWidget.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(new Runnable() {
		            @Override
		            public void run() {
		                //int timer = 0;
		            	SoapObject rpc = new SoapObject(NAME_SPACE, "getLectureInfo");
		        		rpc.addProperty("lecturePlace", placeId);
		        		int[] ids = LectureManager.getAllPlaceId(placeId);
		        		String str = "";
		        		if(ids.length == 0){
		        			str = "000";
		        		}
		        		else{
		        			str += String.valueOf(ids[0]);
		        			for(int i = 1; i < ids.length; i++){
		        				str += ":" + ids[i];
		        			}
		        		}
		        		rpc.addProperty("oldLectures", str);
		        		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		        		envelope.dotNet = false;   
		                envelope.setOutputSoapObject(rpc);
		                HttpTransportSE ht = new HttpTransportSE(URL_LECTURE);
		                
		                try {   
		                    ht.call(NAME_SPACE + "getLectureInfo", envelope);  
		                    if (envelope.getResponse() != null) {            	
//		                    	System.out.println(((SoapObject)envelope.bodyIn).getProperty(0).toString());
		                    	if(!((SoapObject)envelope.bodyIn).getProperty(0).toString().equals("0")){
		                    		
		                    		List<Map<String, String>> list = new ArrayList<Map<String,String>>();
		                    		for(int i = 0; i < ((SoapObject)envelope.bodyIn).getPropertyCount(); i++){
		                    			String s = ((SoapObject)envelope.bodyIn).getProperty(i).toString();
		                    			System.out.println(s);
		                    			String[] strings = s.split("<::>");
//		                    			System.out.println(strings.length);
		                    			Map<String, String> map = new HashMap<String, String>();
		                    			map.put("user_name", strings[0]);
		                    			map.put("user_alias", strings[1]);
		                    			map.put("user_image", strings[2]);
		                    			map.put("user_gender", strings[3]);
		                    			map.put("user_constellation", strings[4]);
		                    			map.put("user_age", strings[5]);
		                    			if(strings.length > 6){
		                    				map.put("user_state", strings[6]);
		                    			}	
		                    			list.add(map);
		                    		}
		                    	}
		                    	else{
		                    		
		                    	}
		            		                
		                    } 
		                } catch (Exception e) {   
		                    e.printStackTrace();   
		                } 
		            }
		        }).start();
			}
		});
		handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case 0:
                	
                }
                super.handleMessage(msg);
            }

        };
		
		selectPlaceWidget = (ImageButton)findViewById(R.id.lecture_select_place);
		selectTypeWidget = (ImageButton)findViewById(R.id.lecture_select_type);
		selectTimeWidget = (ImageButton)findViewById(R.id.lecture_select_time);
		
		lectureListWidget = (ListView)findViewById(R.id.lecture_list);
		SimpleAdapter adapter = new SimpleAdapter(this, getLectureListData(), R.layout.lecture_list_item, 
				new String[]{"lecture_item_title","lecture_item_person","lecture_item_place","lecture_item_time","lecture_item_type"}, 
				new int[]{R.id.lecture_item_title,R.id.lecture_item_person,R.id.lecture_item_place,R.id.lecture_item_time,R.id.lecture_item_type});
		lectureListWidget.setAdapter(adapter);
		
		lectureListWidget.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Map<String, Object> map = (Map<String, Object>)lectureListWidget.getItemAtPosition(arg2);
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("lecture_title", (String)map.get("lecture_item_title"));
				bundle.putString("lecture_person", (String)map.get("lecture_item_person"));
				bundle.putString("lecture_place", (String)map.get("lecture_item_place"));
				bundle.putString("lecture_time", (String)map.get("lecture_item_time"));
				bundle.putString("lecture_type", (String)map.get("lecture_item_type"));
				bundle.putString("lecture_introduce", (String)map.get("lecture_item_introduce"));
				intent.putExtras(bundle);
				intent.setClass(LectureListActivity.this, LectureDetailActivity.class);
				startActivity(intent);
			}
			
		});
	}
	
	private List<Map<String, Object>> getLectureListData(){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		List<Lecture> lectures = LectureManager.getAllLectures(placeId);
		Map<String, Object> map = null;
		Lecture lecture = null;
		
		for(int i = 0; i < lectures.size(); i++){
			lecture = lectures.get(i);
			map = new HashMap<String, Object>();
			map.put("lecture_item_title", lecture.getTitle());
			map.put("lecture_item_person", lecture.getPerson());
			map.put("lecture_item_place", lecture.getPlaceRoom());
			
			Timestamp startTime = lecture.getStartTime();
			Timestamp endTime = lecture.getEndTime();
			SimpleDateFormat format = new SimpleDateFormat("HH:mm");
			
			map.put("lecture_item_time", (startTime.getMonth() + 1) + "." + (startTime.getDate() + 1) + 
					" " + format.format(startTime) +
					" - " + format.format(endTime));
			
			map.put("lecture_item_type", lecture.getType());
			map.put("lecture_item_introduce", lecture.getIntroduce());
			list.add(map);
		}
		
		
		return list;
	}

}
